﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Sworm;

namespace SwormTests.Types
{
    public class user_conversions : TestBase
    {
        public user_conversions(DbToTest type) : base(type) { }

        protected override TypeAnalyzer CreateTypeAnalyzer()
        {
            return new CustomAnalyzer();
        }

        class my_table
        {
            public Lazy<string> unsupported_type { get; set; }
        }

        [Test]
        public void todo934()
        {
            var instance = new my_table();
            instance.unsupported_type = new Lazy<string>(() => "hello");

            DB.Insert(instance);

            var fromDb = DB.Query.Simple<my_table>().List().Single();
            Assert.AreEqual("hello", fromDb.unsupported_type.Value);
        }

        [Test]
        public void todo234()
        {
            Assert.Inconclusive("TODO there's a lot of code paths left that probably aren't covered");
        }

        private class CustomAnalyzer : TypeAnalyzer
        {
            public override void SimplifyColumnType(ref Type type)
            {
                if (type == typeof(Lazy<string>))
                {
                    type = typeof(string);
                }

                base.SimplifyColumnType(ref type);
            }

            public override Func<object, object> GetDefaultToDbConverter(Type paramType)
            {
                if (paramType == typeof(Lazy<string>))
                {
                    return instance => ((Lazy<string>)instance).Value;
                }

                return base.GetDefaultToDbConverter(paramType);
            }

            public override Func<DbAccessor, object> GetFromDbConverter(Member member)
            {
                if (member.Type == typeof(Lazy<string>))
                {
                    return accessor =>
                    {
                        string val = accessor.GetString();
                        return new Lazy<string>(() => val);
                    };
                }

                return base.GetFromDbConverter(member);
            }
        }
    }
}
